<script setup lang="ts">
// bytemd https://github.com/bytedance/bytemd.git
import { Editor, Viewer } from "@bytemd/vue-next";
import gfm from "@bytemd/plugin-gfm";
import highlight from "@bytemd/plugin-highlight";
import gemoji from "@bytemd/plugin-gemoji";
import "bytemd/dist/index.css";
import "highlight.js/styles/idea.css";
import "github-markdown-css/github-markdown.css";
import { computed, ref, watch } from "vue";
import { updateValue } from "./index";

const plugins = [gfm(), highlight(), gemoji()];

const props = defineProps({
  value: {
    type: String,
    default: "",
    required: true
  },
  placeholder: {
    type: String,
    default: "请输入内容，支持Markdown语法",
    required: false
  },
  readonly: {
    type: Boolean,
    default: false
  }
});

// 监听props.value的变化并同步到updateValue
watch(
  () => props.value,
  newVal => {
    updateValue.value = newVal;
  },
  { immediate: true }
);

const isEdit = computed(() => {
  return !props.readonly;
});

function handleChange(v) {
  updateValue.value = v;
}
</script>
<template>
  <div>
    <Editor
      v-if="isEdit"
      :value="updateValue"
      :placeholder="placeholder"
      :plugins="plugins"
      @change="handleChange"
    />
    <Viewer v-else :value="updateValue" :plugins="plugins" />
  </div>
</template>
<style lang="scss">
.bytemd {
  height: calc(100vh - 100px);
}
.markdown-body {
  box-sizing: border-box;
  min-width: 200px;
  max-width: 980px;
  margin: 0 auto;
  padding: 25px;
  ol {
    padding-left: 1em;
    margin: 0;
    list-style: decimal !important;
  }
  ul {
    padding-left: 1em;
    margin: 0;
    list-style: disc !important;
  }
}
.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body pre,
.markdown-body details {
  margin-top: 0;
  margin-bottom: 16px;
}
</style>
